#include "./head.h"
#define PTHREAD_NUM 4

int pipe_fd[2];

void signal_func(int num){


    write(pipe_fd[1],"exit",5);

}



int main()
{
    int sock_fd;
    status_t status;
    pipe(pipe_fd);

    pid_t pid = fork();

    if (pid < 0)
    {
        ERR_LOG("fork error");
    }else if (pid == 0)//子进程
    {
        setpgid(0,0);

    }else{

        signal(2,signal_func);

    }

    init_status(&status,PTHREAD_NUM);

    init_threadpool(&status);
    
    init_socket(&sock_fd,"8080","192.168.250.100");
    
    int epoll_fd = epoll_create(1);

    add_epoll(epoll_fd,sock_fd);//函数定义跳转：F12，Alt + 箭头
    add_epoll(epoll_fd,pipe_fd[0]);

    while(1){

        struct epoll_event events[2];

        memset(events,0,sizeof(events));

       int epoll_num  = epoll_wait(epoll_fd,events,2,-1);

       for(int i = 0; i < epoll_num;i++){

           int fd = events[i].data.fd;
           if(fd == sock_fd){
               int net_fd = accept(sock_fd,NULL,NULL);
                pthread_mutex_lock(&status.mutex);
                enQueue(&status.queue, net_fd);
                pthread_cond_broadcast(&status.cond);
                pthread_mutex_unlock(&status.mutex);
           }else if(fd == pipe_fd[0]){

                char buff[1024] = {0};
                read(pipe_fd[0],buff,sizeof(buff));
                printf("signal coming\n");

                //先通知子线程退出，再回收
                for (int i = 0; i < status.thread_num; i++)
                {
                    pthread_cancel(status.thread_ids[i]);//通知
                }
                for (int i = 0; i < status.thread_num; i++)
                {
                    pthread_join(status.thread_ids[i],NULL);//捕捉子线程是否退出
                }
                
                pthread_exit(NULL);

           }

       }

    }        

       



    printf("Hello worli\n");
    return 0;
}

